package com.haiertvbic.tvnow.widget;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.client.ClientProtocolException;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.BaseAdapter;

import com.haiertvbic.tvnow.R;
import com.haiertvbic.tvnow.model.ProgramDetail;
import com.haiertvbic.tvnow.model.ScreenShot;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.network.ImageUtil;
import com.haiertvbic.tvnow.network.NetUtil;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.TimeUtil;

public class RealTimePictrue {

	private static final String TAG = "RealTimeChannel";
	private static final int GET_CHANNEL_PICTURE = 1000;
	protected static final int GET_PROGRESS_AND_LASTTIME = 1004;
	// 服务器无正确的节目数据
	protected static final int NO_PROGRAM_INFO = 1005;

	private Timer scheduleTT = null;
	private BaseAdapter adapter;
	private String cid;
	private Context context;
	private ArrayList<RealTime> realTimes;
	private RealTime realTime;

	private int endTime;

	private boolean stopTime;
	long delay = 3000;
	Handler errorHandler;
	Handler sucHandler;

	public RealTimePictrue(final BaseAdapter adapter,
			ArrayList<RealTime> realTimeList, Context context) {
		this.context = context;
		this.adapter = adapter;
		this.realTimes = realTimeList;
		initHandler();
		stopTime = false;
	}

	public RealTimePictrue(final BaseAdapter adapter, RealTime realTime,
			Context context) {
		this.context = context;
		this.adapter = adapter;
		this.realTime = realTime;
		initHandler();
	}

	private void initHandler() {
		scheduleTT = new Timer();
		sucHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case GET_CHANNEL_PICTURE:
					realTime.noNetwork.setVisibility(View.INVISIBLE);
					realTime.noPictrue.setVisibility(View.GONE);
					final ScreenShot screen = (ScreenShot) msg.obj;
					startChannelAnim(screen);
					break;
				case GET_PROGRESS_AND_LASTTIME:
					realTime.noNetwork.setVisibility(View.INVISIBLE);
					realTime.noPictrue.setVisibility(View.GONE);
					String time = "";
					if (endTime == 0) {
						time = context.getString(R.string.program_end1);
					} else if (endTime == 1) {
						// 000minute
						time = context.getString(R.string.program_end2);
						time = time.replace("0", "");
						time = endTime + time;
					} else if (endTime > 1) {
						// minutes
						time = context.getString(R.string.program_end3);
						time = time.replace("0", "");
						time = endTime + time;
					}
					realTime.lastTime.setText(time);
					adapter.notifyDataSetChanged();
					break;
				default:
					break;
				}
			}

		};
		errorHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case EPGWeb.SERVER_NO_DATA:
					realTime.noNetwork.setVisibility(View.GONE);
					realTime.noPictrue.setVisibility(View.VISIBLE);
					adapter.notifyDataSetChanged();
					break;
				case EPGWeb.SYS_TIME_ERROR:
					realTime.noNetwork.setVisibility(View.INVISIBLE);
					realTime.noPictrue.setVisibility(View.GONE);
					String time = context.getString(R.string.sys_time_error);
					realTime.lastTime.setText(time);
					adapter.notifyDataSetChanged();
					break;
				case EPGWeb.NO_NETWORK:
					realTime.noNetwork.setVisibility(View.VISIBLE);
					realTime.noPictrue.setVisibility(View.GONE);
					time = "";
					realTime.lastTime.setText(time);
					final ScreenShot screenNoNet = (ScreenShot) msg.obj;
					startChannelAnim(screenNoNet);
					break;

				case NO_PROGRAM_INFO:
					time = "";
					realTime.lastTime.setText(time);
					adapter.notifyDataSetChanged();
					break;
				default:
					break;
				}
			}
		};

	}

	public void timeStop() {
		SLog.d(TAG + cid, "定时器停止");
		stopTime = true;
		if (scheduleTT != null) {
			scheduleTT.cancel();
			scheduleTT = null;
			SLog.d(TAG, "stopTime状态===" + stopTime);
		}
	}

	public void getSinglePic() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(delay);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				imageSchedule();
				cid = realTime.cid + "";
				epgSchedule();
			}
		}).start();
	}

	public void getPic() {
		if (scheduleTT == null)
			scheduleTT = new Timer();
		if (scheduleTT != null) {
			scheduleTT.schedule(new TimerTask() {

				@Override
				public void run() {
					realTime = realTimes.get(new Random().nextInt(realTimes
							.size()));
					cid = realTime.cid + "";

					imageSchedule();
					epgSchedule();
					System.gc();
					delay = 7 * 1000 * (1 + Integer.valueOf(ImageUtil.offset));
					SLog.d(TAG + cid, "stopTime状态===" + stopTime);
					if (stopTime) {
						return;
					} else {
						SLog.d(TAG, "下次请求将延迟==" + delay);
						getPic();
					}
				}
			}, delay);
		}
	}

	/**
	 * 获取当前epg信息
	 */
	private void epgSchedule() {
		// 取节目信息
		ArrayList<ProgramDetail> program = null;
		program = EPGWeb.getCurrentProgram(context, cid);
		// ArrayList<ProgramDetail> programs = new ArrayList<ProgramDetail>();
		// programs.add(program.get(0));
		// ProgramDetail p = program.get(1);
		// p.setDate(program.get(0).getDate());
		// programs.add(p);
		// program = TimeUtil.filterByTime(programs);
		realTime.pro = program != null && program.size() > 0 ? program.get(0)
				: null;
		if (realTime.pro != null) {
			SLog.d(TAG, "所在频道==" + cid + "==当前节目名字==" + realTime.pro.getPn());
			sucHandler.sendEmptyMessage(GET_PROGRESS_AND_LASTTIME);
			int passedTime = TimeUtil.getProgramPassedTime(realTime.pro,
					context);
			int programTimeLength = TimeUtil.getProgramTimeLength(realTime.pro);
			SLog.d(TAG + cid, "所在频道==" + cid + "已经播出了" + passedTime + "分钟");
			SLog.d(TAG + cid, "所在频道==" + cid + "节目一共" + programTimeLength
					+ "分钟");
			if (programTimeLength > 0 && passedTime > 0
					&& passedTime < (programTimeLength + 1)) {
				endTime = programTimeLength - passedTime;
				realTime.progress = (int) ((passedTime / (float) programTimeLength) * 100);
				sucHandler.sendEmptyMessage(GET_PROGRESS_AND_LASTTIME);
			} else if (programTimeLength < passedTime
					&& TimeUtil.getCurrentMinute("HH:mm:ss") < programTimeLength) {
				errorHandler.sendEmptyMessage(EPGWeb.SYS_TIME_ERROR);
			} else if (programTimeLength < 1) {
				// 当前节目的时间是错误的
				errorHandler.sendEmptyMessage(NO_PROGRAM_INFO);
			} else {
				errorHandler.sendEmptyMessage(NO_PROGRAM_INFO);
			}
		} else {
			errorHandler.sendEmptyMessage(NO_PROGRAM_INFO);
		}
	}

	/**
	 * 获取图片
	 * 
	 * @param
	 */
	private void imageSchedule() {
		String cid = realTime.cid + "";
		ScreenShot screen = null;
		if (NetUtil.getNetworkInfo(context)) {
			try {
				ArrayList<ScreenShot> screens;
				screens = EPGWeb.getChannelPIPXML(context, cid, 1);
				if (screens != null && screens.size() > 0) {
					screen = screens.get(0);
					if (screen.getBm() != null) {
						Message msg = Message.obtain();
						msg.what = GET_CHANNEL_PICTURE;
						msg.obj = screen;
						sucHandler.sendMessage(msg);
					}
				} else {
					// 网络可用而没有得到新图
					errorHandler.sendEmptyMessage(EPGWeb.SERVER_NO_DATA);
					SLog.d(TAG + cid, "频道号" + cid + "网络可用而没有得到新图");
				}
			} catch (ClientProtocolException e) {
				// 网络超时
				errorHandler.sendEmptyMessage(EPGWeb.SERVER_NO_DATA);
				SLog.d(TAG + cid, "频道号" + cid + "网络超时");
				e.printStackTrace();
			} catch (IOException e) {
				// 网络超时
				errorHandler.sendEmptyMessage(EPGWeb.SERVER_NO_DATA);
				SLog.d(TAG + cid, "频道号" + cid + "网络超时");
				e.printStackTrace();
			}
		} else {
			// 无网络得不到图片,从本地取
			screen = PipCache.getBmFromLocal(context, cid);
			Message msg = Message.obtain();
			msg.what = EPGWeb.NO_NETWORK;
			msg.obj = screen;
			errorHandler.sendMessage(msg);
			SLog.d(TAG, "频道号" + cid + "无网络得不到图片,从本地取");
		}
		if (screen != null) {
			PipCache.setPipMap(screen, cid);
		}
	}

	/**
	 * 开启更换频道图片的动画
	 * 
	 * @param bms
	 */
	private void startChannelAnim(final ScreenShot screen) {
		final AlphaAnimation animIn = new AlphaAnimation(0, 1);
		animIn.setDuration(1000);
		AlphaAnimation animOut = new AlphaAnimation(1, 0);
		animOut.setDuration(500);
		animOut.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				realTime.image.clearAnimation();
				realTime.image.setImageBitmap(screen.getBm());// 要入的动画
				realTime.image.startAnimation(animIn);
				adapter.notifyDataSetChanged();
			}
		});
		if (realTime.image != null) {
			realTime.image.startAnimation(animOut);
			animOut.startNow();
			adapter.notifyDataSetChanged();
		}
	}
}
